/* =============================================================
 * common-utils.js v1.1.1
 * =============================================================
 * Original written by Ysy
 * =============================================================
 * Date 04/06/2020
 * ============================================================ */

export default class CommonUtils {

  /*变量判断------------------------------------------------------------------------------start*/
  /**
   * 判断变量为字符串
   * @param str 需要判断的字符串
   * @returns {boolean}
   */
  static isString(str) {
    // typeof  对于丰富的对象实例只能返回"Object"字符串  例如：typeof [] 返回的是object
    return str && Object.is("string", typeof str);
  }

  /**
   * 判断变量为数字
   * @param num 需要判断的数字
   * @returns {boolean}
   */
  static isNumber(num) {
    return num && Object.is("number", typeof num);
  }

  /**
   * 判断变量为对象
   * @param obj 需要判断的对象
   * @returns {boolean}
   */
  static isObject(obj) {
    return obj && obj instanceof Object;
  }

  /**
   * 判断变量为数组
   * @param arr 需要判断的数组
   * @returns {boolean}
   */
  static isArray(arr) {
    return arr && arr instanceof Array;
  }

  /**
   * 判断变量为空
   * @param param
   * @returns {boolean}
   */
  static isEmpty(param) {
    return typeof (param) === 'undefined' || typeof (param) === 'null' || (!param && param !== 0)
  }

  /*变量判断------------------------------------------------------------------------------end*/

  /*浏览器操作------------------------------------------------------------------------------start*/

  /**
   * 获取url中的参数
   * @param key  想要获取的url参数
   * @returns {string|null}
   */
  static getUrlParameter(key) {
    // let reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)");
    // let r = window.location.search.substr(1).match(reg);
    // if (r != null) return unescape(r[2]);

    const url = this.getUrlAll()
    const urlStr = url.split('?')[1]
    const urlSearchParams = new URLSearchParams(urlStr)
    const result = Object.fromEntries(urlSearchParams.entries())
    return result[key] || ``
  }

  /**
   * 获取url
   * @returns {string}
   */
  static getUrlAll() {
    return window.location.href;
  }

  /**
   * 获取url路径
   * @returns {string}
   */
  static getUrlPath() {
    return window.location.pathname;
  }

  /**
   * 自定义命名下载文件
   * @param url  目标文件地址
   * @param fileName  自定义的文件名
   */
  static downloadWithCustomName(url, fileName) {
    this.getBlob(url, (blob) => {// 获取blob 格式文件值
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
        return false;
      }

      let link = document.createElement("a");
      let body = document.querySelector("body");

      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;

      // fix Firefox
      link.style.display = "none";
      body.appendChild(link);

      link.click();
      body.removeChild(link);

      window.URL.revokeObjectURL(link.href);
    });
  }

  /**
   * 获取 blob
   * @param url 目标文件地址
   * @param callback 回调函数
   */
  static getBlob(url, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (Object.is(xhr.status, 200)) {
        callback(xhr.response);
      }
    };
    xhr.send();
  }

  /**
   * @Author Ysy
   * @Description // 根据url链接下载图片
   * @Date 15:21 2022/12/8
   * @param imgSrc
   * @param fileName
   **/
  static downloadImage(imgSrc, fileName) {
    let image = new Image()
    // 解决跨域 Canvas 污染问题
    image.setAttribute("crossOrigin", "anonymous")
    image.src = imgSrc

    image.onload =  _=> {

      const canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      const context = canvas.getContext('2d')
      context.drawImage(image, 0, 0, image.width, image.height)
      canvas.toBlob((blob) => {
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.download = name || 'photo'
        a.href = url
        a.click()
        a.remove()
        // 用完释放URL对象
        URL.revokeObjectURL(url)
      })
    }
  }

  static isMobile() {
    return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
  }

  // 判断浏览器是否支持webp
  static checkWebpSupport() {
    let WebP = new Image()

    WebP.onload = WebP.onerror = function () {
      return (WebP.height === 2)
    }
    WebP.src = '';
  }

  /*浏览器操作--------------------------------------------------------------------------------end*/

  /*常用方法--------------------------------------------------------------------------------start*/
  static sleep(number) {
    let now = new Date();
    let exitTime = now.getTime() + number * 1000;
    while (true) {
      now = new Date();
      if (now.getTime() > exitTime)
        return false;
    }
  }

  static copy(value) {
    let oInput = document.createElement("input");
    // 这边为链接地址this.liveLink='www.baidu.com'
    oInput.value = value;
    document.body.appendChild(oInput);
    oInput.select();
    document.execCommand("Copy");
    oInput.remove();
  }

  /*常用方法--------------------------------------------------------------------------------end*/

};

